<template>
	<el-dialog v-model="currentVisible" :class="$style['dialog-audio']" :title="title" :close-on-click-modal="false"
		:close-on-press-escape="false" @closed="handleCloseDialog">
		<div :class="$style['sub-title']">列表中展示当前正在执行播报任务的终端设备，您可以批量停止终端设备的播报任务</div>
		<dl :class="$style['service-select-wrapper']">
			<dt>选择广播服务器</dt>
			<dd>
				<el-select v-model="serviceID" placeholder="选择广播服务器" @change="handleChangeService">
					<template :key="item.device_id" v-for="item in serviceOptions">
						<el-option :label="item.device_name" :value="item.device_id" />
					</template>
				</el-select>
			</dd>
		</dl>

		<h6 :class="$style['required-title']">选择播放终端设备</h6>
		<el-input v-model="terminalKeyword" placeholder="请输入需要筛选的终端设备" clearable @input="handleFilterTerminal">
			<template #prefix>
				<el-icon class="el-input__icon">
					<Search />
				</el-icon>
			</template>
		</el-input>

		<div :class="$style['terminal-table']">
			<el-table :data="terminalOptions" ref="refTable" row-key="device_id" height="100%"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="50" :selectable="selectableRow" />
				<el-table-column prop="device_name" label="设备名称" align="center" />
				<el-table-column prop="taskName" label="任务名称" align="center" />
				<el-table-column label="操作" align="center">
					<template #default="{ row }">
						<div style="display: flex; gap: 10px;" v-if="!row.children">
							<el-link :underline="false" :icon="CircleCheckFilled" type="success" style="font-size:12px;"
								v-if="row.status_id == 30" @click="handleCommand(row, 1)">开启</el-link>
							<el-link style="font-size:12px;" :underline="false" :icon="CircleCloseFilled" type="warning"
								@click="handleCommand(row, 0)" v-if="row.status_id == 34">关闭</el-link>
						</div>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<div :class="$style['dialog-button-wrapper']">
			<el-button @click="handleCloseDialog">取消</el-button>
			<el-button type="primary" :loading="loading" :disabled="!terminalID.length"
				@click="cancelTask">停止任务</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { ref, watch, onBeforeUnmount } from 'vue'
import VueTypes from 'vue-types'
import { ElMessage } from 'element-plus'
import { Search, QuestionFilled, CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'

import http from '@/utils/http'
import { filterListData } from '@/utils/tools'

export default {
	name: 'dialog-cancel-audio-task',
	components: {
		Search,
		QuestionFilled,
		CircleCheckFilled,
		CircleCloseFilled
	},
	props: {
		modelValue: VueTypes.bool.def(false),
		title: VueTypes.string.def('批量停止广播任务')
	},
	emits: ['update:value', 'complete'],
	setup(props, { emit }) {
		const refAudioDialog = ref(null)
		const currentVisible = ref(false)
		const loading = ref(false)
		const serviceID = ref('')
		const serviceOptions = ref([])
		const terminalKeyword = ref('')
		const terminalID = ref([])
		const terminalOptions = ref([])

		let filterKeyword = filterListData()

		const open = (data = {}) => {
			getService()

			currentVisible.value = true
		}

		const getService = () => {
			http.get('/v1/broadcast/getServer', {}).then(res => {
				if (res.code == 1) {
					serviceOptions.value = Array.isArray(res.data) ? res.data : []
					serviceID.value = serviceOptions.value[0].device_id

					if (serviceID.value) {
						handleChangeService(serviceID.value)
					}
				}
			})
		}

		const getTerminal = (id) => {
			http.get('/v1/broadcast/getTask', { params: { device_id: id } }).then(res => {
				if (res.code == 1) {
					terminalOptions.value = res.data
					console.log(terminalOptions.value)
					filterKeyword.setData(res.data)
				}
			})
		}

		const handleChangeService = (value) => {
			getTerminal(value)
		}

		const handleSelectionChange = (rows) => {
			terminalID.value = rows.map(item => item.device_id)
		}

		const handleFilterTerminal = (value) => {
			terminalOptions.value = filterKeyword.filter(value, 'device_name')
		}

		const cancelTask = () => {
			const postData = {
				device_id: terminalID.value,
				serverIp: '',
				url: ''
			}

			const currentService = serviceOptions.value.find(item => item.device_id === serviceID.value)

			if (currentService) {
				postData.serverIp = currentService.ip
				postData.url = currentService.url
			}

			loading.value = true

			http.post('/v1/broadcast/batchStopTask', postData).then(res => {
				if (res.code == 1) {
					ElMessage.success('处理成功')
					handleCloseDialog()
					emit('complete')
				}

				loading.value = false
			}).catch(() => {
				loading.value = false
			})
		}

		const handleCloseDialog = () => {
			currentVisible.value = false
			serviceOptions.value = []
			terminalOptions.value = []
			serviceID.value = ''
			terminalID.value = []

			emit('update:value', false)
		}

		const handleCommand = (row, cmd) => {
			http.post('/v2/broadcast/setTerminalZoneStatus', { device_id: row.device_id, command: cmd }).then(res => {
				if (res.code == 1) {
					ElMessage.success('处理成功')
					resetTableData()
				}
			})
		}

		const selectableRow = (row) => {
			return row.children
		}
		watch(
			() => props.modelValue,
			visible => {
				currentVisible.value = visible
			}
		)

		onBeforeUnmount(() => {
			currentVisible.value = false
			filterKeyword.destroy()

			filterKeyword = null
		})

		return {
			refAudioDialog,
			currentVisible,
			loading,
			serviceOptions,
			terminalOptions,
			serviceID,
			terminalID,
			terminalKeyword,
			handleChangeService,
			handleSelectionChange,
			handleFilterTerminal,
			handleCloseDialog,
			handleCommand,
			cancelTask,
			open,
			selectableRow,
			CircleCheckFilled,
			CircleCloseFilled
		}
	}
}
</script>

<style lang="scss" module>
.dialog-audio {
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	max-width: 600px;
	height: calc(100vh - 20vh);
	max-height: 600px;
	margin: 10vh auto 0;

	& [class~="el-dialog__body"] {
		box-sizing: border-box;
		flex: 1 0 0;
		display: flex;
		flex-direction: column;
		gap: 10px;
		width: 100%;
		height: 0;
		padding: 20px 0 0 0;
	}

	& [class~="el-dialog__header"] {
		padding-bottom: 0;
	}
}

.sub-title {
	height: 20px;
	line-height: 20px;
	font-size: 12px;
	font-weight: 400;
	color: #888;
}

.required-title {
	&:before {
		content: "*";
		margin-right: 4px;
		color: #F56C6C;
	}
}

.service-select-wrapper {
	display: flex;
	align-items: center;
	gap: 10px;

	& dt {
		flex: 100px 0 0;
	}

	& dd {
		flex: 1;
	}
}

.terminal-table {
	overflow: auto;
	display: block;
	box-sizing: border-box;
	flex: 1 0 0;
	height: 0;
	padding: 0;
	background-color: #FFF;
	border-radius: 5px;
}

.dialog-button-wrapper {
	display: flex;
	justify-content: center;
	margin-top: 12px;

	& [class~="el-button"] {
		width: 100px;
	}
}
</style>
